import { readdirSync, writeFileSync } from 'fs';
import { isAbsolute, join } from 'path';
import { terminal } from 'terminal-kit';
import { useCloudBaseContext } from './cloudbase-context';
import { ScfConfig, PackageWithScf } from './types';
import { isDir, isFile, loadJsonObject } from './utils';

export function resourceAggregation(dir?: string) {
  const basePath = process.cwd();
  const workingPath = selectWorkingPath(basePath, dir);
  const ctx = useCloudBaseContext(workingPath);
  const projects: ScfConfig[] = [];

  const loadSubprojectPkg = (path: string) => {
    const dirPath = join(ctx.functionRoot, path);
    if (!isDir(dirPath)) return;
    const pkgPath = join(dirPath, 'package.json');
    if (isFile(pkgPath)) {
      const pkgData = loadJsonObject<PackageWithScf>(pkgPath);
      if (pkgData?.scf != null && pkgData?.scf.name) {
        projects.push(pkgData.scf);
      }
    }
  };

  try {
    readdirSync(ctx.functionRoot).forEach(loadSubprojectPkg);
    if (projects.length > 0) {
      projects.forEach(conf => ctx.addScfConfig(conf));
      const name = projects.length > 1 ? 'projects' : 'project';
      terminal('Inject ').yellow(projects.length);
      terminal(` ${name} config into `).cyan('cloudbaserc.json\n');
    } else {
      terminal('There are currently ').red('no subprojects');
      terminal(' to update\n');
    }
    try {
      writeFileSync(ctx.rootFiles.cloudbase, JSON.stringify(ctx.cloudbase, null, 2));
      terminal('Update ').cyan('cloudbaserc.json').green(' success');
    } catch (e) {
      terminal('Update ').cyan('cloudbaserc.json').red(' error');
    }
    process.stdout.write('\n');
  } catch (e) {
    console.error(e);
  }
}

function selectWorkingPath(basePath: string, dir?: string): string {
  if (dir == null || dir.trim() === '') {
    return basePath;
  }
  if (isAbsolute(dir)) {
    return dir;
  }
  return join(basePath, dir);
}
